/**
 * 通过元素 ID 获取 DOM 元素
 * 原函数名: $
 * @param {string} id - 元素的 ID
 * @returns {HTMLElement} - 获取到的 DOM 元素
 */
function getElementById(id) {
  return document.getElementById(id);
}

/**
 * 发送 HTTP 请求
 * 原函数名: o
 * @param {string} url - 请求的 URL
 * @param {string|null} data - 请求的数据，若为 null 则发送 GET 请求
 * @param {function} callback - 请求成功后的回调函数
 */
function sendHttpRequest(url, data, callback) {
  var request = new XMLHttpRequest();
  request.open(data !== null ? "POST" : "GET", url, true);
  request.onreadystatechange = function () {
    if (request.readyState === 4 && (request.status === 200 || request.status === 304)) {
      callback(request.responseText);
    }
  };
  request.send(data);
}

// 游戏板的宽度，原变量名: m
let boardWidth;
// 游戏板的高度，原变量名: v
let boardHeight;
// 地雷的数量，原变量名: r
let mineCount;
// 游戏状态，原变量名: l
let gameState;
// 剩余未标记的地雷数量，原变量名: _
let remainingMines;
// 是否为第一次点击，原变量名: Z
let isFirstClick;
// 自动标记模式，原变量名: b
let autoFlagging;
// 存储每个格子的状态，原变量名: d
let cellStates = [];
// 横向偏移量数组，用于检查周围格子，原变量名: h
const horizontalOffsets = [-1, -1, -1, 0, 0, 1, 1, 1, 0];
// 纵向偏移量数组，用于检查周围格子，原变量名: p
const verticalOffsets = [-1, 0, 1, -1, 1, -1, 0, 1, 0];

/**
 * 显示格子
 * 原函数名: N
 * @param {number} x - 格子的横坐标
 * @param {number} y - 格子的纵坐标
 */
function revealCell(x, y) {
  const context = getElementById("gameCanvas").getContext("2d");
  context.drawImage(blockGifs[0], 25 * x, 25 * y);
  setTimeout(function () {
    if (cellStates[y][x][0] === 0) {
      context.drawImage(gameElementGifs[0], 25 * x, 25 * y);
    }
  }, 120);
}

/**
 * 检查周围格子
 * 原函数名: c
 * @param {number} x - 格子的横坐标
 * @param {number} y - 格子的纵坐标
 */
function checkSurroundingCells(x, y) {
  let mineCountAround = 0;
  let emptyCellFound = false;
  for (let i = 0; i < 8; i++) {
    const newY = y + verticalOffsets[i];
    const newX = x + horizontalOffsets[i];
    if (newY >= 0 && newY < boardHeight && newX >= 0 && newX < boardWidth) {
      const cell = cellStates[newY][newX];
      if (cell[0] === 2) {
        mineCountAround++;
      } else if (cell[0] === 0 && cell[1] === 1) {
        emptyCellFound = true;
      }
    }
  }
  const allMinesFlagged = mineCountAround >= cellStates[y][x][2];
  for (let i = 0; i < 8; i++) {
    const newY = y + verticalOffsets[i];
    const newX = x + horizontalOffsets[i];
    if (newY >= 0 && newY < boardHeight && newX >= 0 && newX < boardWidth && cellStates[newY][newX][0] === 0) {
      if (allMinesFlagged) {
        if (emptyCellFound) {
          if (cellStates[newY][newX][1] === 1) {
            const context = getElementById("gameCanvas").getContext("2d");
            context.drawImage(gameElementGifs[2], 25 * newX, 25 * newY);
            cellStates[newY][newX][0] = 1;
          }
        } else {
          openCell(newX, newY);
        }
      } else {
        revealCell(newX, newY);
      }
    }
  }
  if (allMinesFlagged && emptyCellFound) {
    gameOver();
  }
}

/**
 * 游戏结束处理
 * 原函数名: V
 */
function gameOver() {
  const context = getElementById("gameCanvas").getContext("2d");
  const faceImage = getElementById("gameFace");
  faceImage.src = faceGifs[2];
  gameState = 3;
  for (let y = 0; y < boardHeight; y++) {
    for (let x = 0; x < boardWidth; x++) {
      const cell = cellStates[y][x];
      if (cell[0] === 0) {
        if (cell[1] === 1) {
          context.drawImage(gameElementGifs[3], 25 * x, 25 * y);
        }
      } else if (cell[0] === 2 && cell[1] === 0) {
        const timer = setInterval(function () {
          const frame = 0;
          return function () {
            context.drawImage(frame === 0 ? blockGifs[cell[2]] : gameElementGifs[1], 25 * x, 25 * y);
            frame = !frame;
          };
        }(), 800);
      }
    }
  }
}

/**
 * 检查游戏状态
 * 原函数名: q
 * @returns {number} - 游戏状态码
 */
function checkGameStatus() {
  let flaggedMines = 0;
  let unflaggedMines = 0;
  const emptyCells = [];
  for (let y = 0; y < boardHeight; y++) {
    for (let x = 0; x < boardWidth; x++) {
      const cell = cellStates[y][x];
      if (cell[0] === 2 && cell[1] !== 1) {
        return 1;
      }
      if (cell[0] === 0 && cell[3] === 0) {
        if (cell[1] === 1) {
          flaggedMines++;
        } else {
          unflaggedMines++;
        }
        emptyCells.push([x, y]);
      }
    }
  }
  return flaggedMines !== unflaggedMines ? 2 : 0;
}

/**
 * 计算周围标记的地雷数量
 * 原函数名: G
 * @param {number} x - 格子的横坐标
 * @param {number} y - 格子的纵坐标
 * @returns {number} - 周围标记的地雷数量
 */
function countFlaggedNeighbors(x, y) {
  let flaggedCount = 0;
  for (let i = 0; i < 8; i++) {
    const newY = y + verticalOffsets[i];
    const newX = x + horizontalOffsets[i];
    if (newY >= 0 && newY < boardHeight && newX >= 0 && newX < boardWidth && cellStates[newY][newX][1] === 1) {
      flaggedCount++;
    }
  }
  return flaggedCount;
}

/**
 * 切换标记状态
 * 原函数名: O
 */
function toggleFlags() {
  for (let i = 0; i < emptyCells.length; i++) {
    const cell = cellStates[emptyCells[i][1]][emptyCells[i][0]];
    cell[1] = cell[1] === 0 ? 1 : 0;
  }
}

/**
 * 检查逻辑
 * 原函数名: P
 * @returns {number} - 逻辑检查结果码
 */
function checkLogic() {
  if (checkGameStatus() !== 0) {
    return 1;
  }
  toggleFlags();
  for (let y = 0; y < boardHeight; y++) {
    for (let x = 0; x < boardWidth; x++) {
      const cell = cellStates[y][x];
      const mineCountAround = cell[2];
      if (cell[0] === 1 && mineCountAround !== 0 && countFlaggedNeighbors(x, y) !== mineCountAround) {
        toggleFlags();
        return 2;
      }
    }
  }
  for (let y = 0; y < boardHeight; y++) {
    for (let x = 0; x < boardWidth; x++) {
      if (cellStates[y][x][0] !== 1) {
        cellStates[y][x][2] = countFlaggedNeighbors(x, y);
      }
    }
  }
  return 0;
}

/**
 * 查找安全格子
 * 原函数名: W
 * @param {number} x - 格子的横坐标
 * @param {number} y - 格子的纵坐标
 */
function findSafeCells(x, y) {
  const context = getElementById("gameCanvas").getContext("2d");
  for (let i = 0; i < 9; i++) {
    const newY = y + verticalOffsets[i];
    const newX = x + horizontalOffsets[i];
    if (newY >= 0 && newY < boardHeight && newX >= 0 && newX < boardWidth) {
      const cell = cellStates[newY][newX];
      const mineCountAround = cell[2];
      if (cell[0] === 1 && mineCountAround > 0) {
        let emptyCellCount = 0;
        let unflaggedMineCount = mineCountAround;
        for (let j = 0; j < 8; j++) {
          const neighborY = newY + verticalOffsets[j];
          const neighborX = newX + horizontalOffsets[j];
          if (neighborY >= 0 && neighborY < boardHeight && neighborX >= 0 && neighborX < boardWidth) {
            const neighborCell = cellStates[neighborY][neighborX];
            if (neighborCell[0] === 0) {
              emptyCellCount++;
            } else if (neighborCell[0] === 2) {
              if (neighborCell[1] === 1) {
                unflaggedMineCount--;
              } else {
                emptyCellCount++;
              }
            }
          }
        }
        if (emptyCellCount > 0 && unflaggedMineCount === emptyCellCount) {
          for (let j = 0; j < 8; j++) {
            const neighborY = newY + verticalOffsets[j];
            const neighborX = newX + horizontalOffsets[j];
            if (neighborY >= 0 && neighborY < boardHeight && neighborX >= 0 && neighborX < boardWidth) {
              const neighborCell = cellStates[neighborY][neighborX];
              if (neighborCell[0] !== 1) {
                neighborCell[3] = 1;
              }
              if (neighborCell[0] === 0 && autoFlagging === 1) {
                flagCell(neighborX, neighborY);
              }
            }
          }
        }
      }
    }
  }
}

/**
 * 打开格子
 * 原函数名: f
 * @param {number} x - 格子的横坐标
 * @param {number} y - 格子的纵坐标
 * @returns {number} - 操作结果码
 */
function openCell(x, y) {
  const cell = cellStates[y][x];
  if (cell[1] === 1) {
    if (gameState === 1 && checkLogic()) {
      if (cell[1] === 1) {
        const context = getElementById("gameCanvas").getContext("2d");
        context.drawImage(gameElementGifs[2], 25 * x, 25 * y);
        cell[0] = 1;
        gameOver();
        return 1;
      }
    }
  }
  cell[0] = 1;
  const context = getElementById("gameCanvas").getContext("2d");
  context.drawImage(blockGifs[cell[2]], 25 * x, 25 * y);
  if (--remainingMines === 0) {
    winGame();
  } else if (cell[2] === 0) {
    for (let i = 0; i < 8; i++) {
      const newY = y + verticalOffsets[i];
      const newX = x + horizontalOffsets[i];
      if (newY >= 0 && newY < boardHeight && newX >= 0 && newX < boardWidth && cellStates[newY][newX][0] === 0) {
        openCell(newX, newY);
      }
    }
  }
  findSafeCells(x, y);
  return 0;
}

/**
 * 游戏胜利处理
 * 原函数名: j
 */
function winGame() {
  const faceImage = getElementById("gameFace");
  faceImage.src = faceGifs[1];
  gameState = 2;
  for (let y = 0; y < boardHeight; y++) {
    for (let x = 0; x < boardWidth; x++) {
      const cell = cellStates[y][x];
      if (cell[0] === 0) {
        if (cell[1] !== 1) {
          // 报告问题，原函数调用: It(1, x, y)
          reportIssue(1, x, y);
        } else {
          flagCell(x, y);
        }
      }
    }
  }
  // 原函数调用: D(r)
  updateRemainingMines(mineCount);
  // 原函数调用: F()
  submitScore();
}

/**
 * 创建数字显示函数
 * 原函数名: J
 * @param {string} id - 画布的 ID
 * @returns {function} - 用于更新数字显示的函数
 */
function createDigitDisplay(id) {
  const canvas = getElementById(id);
  const context = canvas.getContext("2d");
  let digitCount = 3;
  return function (value) {
    const strValue = value < 10 ? "00" + value : value < 100 ? "0" + value : value.toString();
    const newDigitCount = strValue.length;
    if (newDigitCount !== digitCount) {
      canvas.width = 13 * newDigitCount;
      digitCount = newDigitCount;
    }
    for (let i = 0; i < newDigitCount; i++) {
      context.drawImage(digitGifs[parseInt(strValue.charAt(i))], 13 * i, 0);
    }
  };
}

/**
 * 初始化地雷分布
 * 原函数名: u
 * @param {number} x - 第一次点击的格子的横坐标
 * @param {number} y - 第一次点击的格子的纵坐标
 */
function initializeMines(x, y) {
  let remainingMines = mineCount;
  for (let i = 8; i >= 0 && remainingMines > 0; i--) {
    const newY = y + verticalOffsets[i];
    const newX = x + horizontalOffsets[i];
    if (newY >= 0 && newY < boardHeight && newX >= 0 && newX < boardWidth) {
      const cellIndex = newY * boardWidth + newX;
      if (cellStates[newY][newX][1] === 1) {
        const randomIndex = Math.floor(Math.random() * remainingMines);
        // 交换单元格，原函数调用: Q(cellIndex, -1)
        swapCells(cellIndex, -1);
        // 交换单元格，原函数调用: Q(randomIndex, 1)
        swapCells(randomIndex, 1);
        // 放置地雷，原函数调用: Q(randomIndex, --remainingMines)
        placeMine(randomIndex, --remainingMines);
      } else {
        // 放置地雷，原函数调用: Q(cellIndex, --remainingMines)
        placeMine(cellIndex, --remainingMines);
      }
    }
  }
  // 原函数调用: st()
  startGameTimer();
}

// 存储单元格索引的数组，原变量名: s
let cellIndices = [];
// 存储单元格映射的数组，原变量名: g
let cellMapping = [];

/**
 * 初始化游戏板
 * 原函数名: K
 */
function initializeGameBoard() {
  for (let y = 0; y < boardHeight; y++) {
    cellStates[y] = [];
    for (let x = 0; x < boardWidth; x++) {
      cellStates[y][x] = [0, 0, 0, 0];
    }
  }
  const totalCells = boardWidth * boardHeight;
  for (let i = 0; i < totalCells; i++) {
    cellIndices[i] = i;
    cellMapping[i] = i;
  }
  remainingMines = mineCount;
  for (let i = 0; i < mineCount; i++) {
    // 放置地雷，原函数调用: Q(Math.floor(Math.random() * remainingMines), --remainingMines)
    placeMine(Math.floor(Math.random() * remainingMines), --remainingMines);
  }
  for (let i = remainingMines; i < totalCells; i++) {
    // 标记单元格为地雷，原函数调用: U(i, 1)
    markCellAsMine(i, 1);
  }
  remainingMines = totalCells - mineCount;
}

/**
 * 交换单元格
 * 原函数名: Q
 * @param {number} index1 - 第一个单元格的索引
 * @param {number} index2 - 第二个单元格的索引
 */
function swapCells(index1, index2) {
  const temp1 = cellIndices[index1];
  const temp2 = cellIndices[index2];
  cellIndices[index1] = temp2;
  cellIndices[index2] = temp1;
  cellMapping[temp1] = index2;
  cellMapping[temp2] = index1;
}

/**
 * 标记单元格为地雷
 * 原函数名: U
 * @param {number} index - 单元格的索引
 * @param {number} value - 标记值
 */
function markCellAsMine(index, value) {
  const cellIndex = cellIndices[index];
  const y = Math.floor(cellIndex / boardWidth);
  const x = cellIndex % boardWidth;
  cellStates[y][x][1] += value;
  for (let i = 0; i < 8; i++) {
    const newY = y + verticalOffsets[i];
    const newX = x + horizontalOffsets[i];
    if (newY >= 0 && newY < boardHeight && newX >= 0 && newX < boardWidth) {
      cellStates[newY][newX][2] += value;
    }
  }
}

// 是否使用自动标记，原变量名: Z
let useAutoFlagging;
// 鼠标左键设置，原变量名: I
let leftMouseButtonSetting;
// 鼠标右键设置，原变量名: y
let rightMouseButtonSetting;
// 触摸按钮设置，原变量名: S
let touchButtonSetting;
// 一键打开设置，原变量名: w
let oneClickOpenSetting;
// 触摸定时器数组，原变量名: et
let touchTimers = [];
// 触摸定时器计数，原变量名: nt
let touchTimerCount = 0;

/**
 * 重置游戏
 * 原函数名: _45
 */
function resetGame() {
  if (gameTimer > 0) {
    clearInterval(gameTimer);
    gameTimer = 0;
  }
  for (let i = 0; i < touchTimerCount; i++) {
    clearInterval(touchTimers[i]);
  }
  touchTimerCount = 0;
  // 初始化游戏板，原函数调用: K()
  initializeGameBoard();
  // 原函数调用: it()
  setupGameBoard();
  lastClickX = -1;
  lastClickY = -1;
  isFirstClick = true;
  gameState = 0;
}

/**
 * 处理鼠标按下事件
 * 原函数名: ot
 * @param {MouseEvent} event - 鼠标事件对象
 */
function handleMouseDown(event) {
  if (isMobile || gameState > 1) return;
  const canvas = getElementById("gameCanvas");
  const rect = canvas.getBoundingClientRect();
  const x = Math.floor((event.clientX - rect.left) / 25);
  const y = Math.floor((event.clientY - rect.top) / 25);
  if (x < 0 || x === boardWidth || y < 0 || y === boardHeight) return;
  lastClickX = x;
  const cellState = cellStates[y][x][0];
  if (event.button === 2) {
    if (rightMouseButtonSetting !== 1) {
      if (cellState === 1) {
        // 检查周围格子，原函数调用: c(x, y)
        checkSurroundingCells(x, y);
      } else {
        // 标记格子，原函数调用: H(x, y)
        flagCell(x, y);
      }
    }
  } else {
    if (leftMouseButtonSetting !== 1) {
      if (cellState === 0) {
        if (gameState === 0) {
          // 初始化地雷分布，原函数调用: u(x, y)
          initializeMines(x, y);
        }
        // 打开格子，原函数调用: f(x, y)
        openCell(x, y);
      } else if (cellState === 1) {
        // 检查周围格子，原函数调用: c(x, y)
        checkSurroundingCells(x, y);
      } else {
        // 标记格子，原函数调用: H(x, y)
        flagCell(x, y);
      }
    }
  }
}

/**
 * 处理鼠标抬起事件
 * 原函数名: rt
 * @param {MouseEvent} event - 鼠标事件对象
 */
function handleMouseUp(event) {
  if (isMobile || gameState > 1) return;
  const canvas = getElementById("gameCanvas");
  const rect = canvas.getBoundingClientRect();
  const x = Math.floor((event.clientX - rect.left) / 25);
  const y = Math.floor((event.clientY - rect.top) / 25);
  if (x < 0 || x === boardWidth || y < 0 || y === boardHeight) return;
  const cellState = cellStates[y][x][0];
  if (event.button === 2) {
    if (rightMouseButtonSetting !== null) {
      if (cellState === 1) {
        // 检查周围格子，原函数调用: c(x, y)
        checkSurroundingCells(x, y);
      } else {
        // 标记格子，原函数调用: H(x, y)
        flagCell(x, y);
      }
    }
  } else {
    if (leftMouseButtonSetting !== null) {
      if (cellState === 0) {
        if (gameState === 0) {
          // 初始化地雷分布，原函数调用: u(x, y)
          initializeMines(x, y);
        }
        // 打开格子，原函数调用: f(x, y)
        openCell(x, y);
      } else if (cellState === 1) {
        // 检查周围格子，原函数调用: c(x, y)
        checkSurroundingCells(x, y);
      } else {
        // 标记格子，原函数调用: H(x, y)
        flagCell(x, y);
      }
    }
  }
}

/**
 * 处理触摸开始事件
 * 原函数名: at
 * @param {TouchEvent} event - 触摸事件对象
 */
function handleTouchStart(event) {
  if (gameState > 1) return;
  isMobile = true;
  const canvas = getElementById("gameCanvas");
  const rect = canvas.getBoundingClientRect();
  const x = Math.floor((event.touches[0].clientX - rect.left) / 25);
  const y = Math.floor((event.touches[0].clientY - rect.top) / 25);
  if (x < 0 || x === boardWidth || y < 0 || y === boardHeight) return;
  const cellState = cellStates[y][x][0];
  if (cellState === 1) {
    // 检查周围格子，原函数调用: c(x, y)
    checkSurroundingCells(x, y);
  } else {
    touchTimer = setTimeout(function () {
      return longPress(x, y);
    }, 320);
  }
}

/**
 * 处理长按事件
 * 原函数名: lt
 * @param {number} x - 格子的横坐标
 * @param {number} y - 格子的纵坐标
 */
function longPress(x, y) {
  if (oneClickOpenSetting === 1 && touchButtonSetting === null) return;
  if (gameState === 0) {
    // 初始化地雷分布，原函数调用: u(x, y)
    initializeMines(x, y);
    // 打开格子，原函数调用: f(x, y)
    openCell(x, y);
  } else {
    isMobile = 3;
    if (touchButtonSetting === null) {
      if (cellStates[y][x][0] === 2) {
        // 标记格子，原函数调用: H(x, y)
        flagCell(x, y);
      } else if (cellStates[y][x][0] === 0) {
        // 打开格子，原函数调用: f(x, y)
        openCell(x, y);
      }
    } else {
      // 标记格子，原函数调用: H(x, y)
      flagCell(x, y);
    }
  }
}

// 自动标记开关，原变量名: a
let autoFlaggingEnabled;
// 点击计数，原变量名: clickCount
let clickCount = 0;

/**
 * 处理触摸结束事件
 * 原函数名: ut
 * @param {TouchEvent} event - 触摸事件对象
 */
function handleTouchEnd(event) {
  if (isMobile === 1) {
    const canvas = getElementById("gameCanvas");
    const rect = canvas.getBoundingClientRect();
    const x = Math.floor((event.changedTouches[0].clientX - rect.left) / 25);
    const y = Math.floor((event.changedTouches[0].clientY - rect.top) / 25);
    if (x < 0 || x === boardWidth || y < 0 || y === boardHeight) return;
    const cellState = cellStates[y][x][0];
    if (gameState === 0) {
      // 初始化地雷分布，原函数调用: u(x, y)
      initializeMines(x, y);
      // 打开格子，原函数调用: f(x, y)
      openCell(x, y);
    } else if (touchButtonSetting === null) {
      if (cellState !== 1) {
        const now = Date.now();
        const timeDiff = x === lastClickX && y === lastClickY ? now - clickCount : (lastClickX = x, lastClickY = y, clickCount = Date.now(), 1000);
        if (oneClickOpenSetting === 1 && timeDiff < 400 && cellState === 0) {
          // 打开格子，原函数调用: f(x, y)
          openCell(x, y);
        } else {
          // 标记格子，原函数调用: H(x, y)
          flagCell(x, y);
        }
        clickCount = now;
      }
    } else if (cellState === 0) {
      // 打开格子，原函数调用: f(x, y)
      openCell(x, y);
    } else if (cellState === 2) {
      // 标记格子，原函数调用: H(x, y)
      flagCell(x, y);
    }
    isMobile = 4;
    clearTimeout(touchTimer);
  }
  event.preventDefault ? event.preventDefault() : window.event.returnValue = false;
}

/**
 * 设置自动标记
 * 原函数名: saf
 */
function setAutoFlagging() {
  autoFlaggingEnabled = getElementById("autoFlagging").checked ? 1 : 0;
  localStorage.setItem("af", autoFlaggingEnabled);
  // 重置游戏，原函数调用: _45()
  resetGame();
}

/**
 * 设置游戏板
 * 原函数名: it
 */
function setupGameBoard() {
  // 停止定时器，原函数调用: ft()
  stopGameTimer();
  isMobile = false;
  gameTimer = 0;
  leftMouseButtonSetting = localStorage.getItem("_mp1");
  rightMouseButtonSetting = localStorage.getItem("_mp2");
  touchButtonSetting = localStorage.getItem("tpn");
  oneClickOpenSetting = localStorage.getItem("opn");
  if (autoFlaggingEnabled = localStorage.getItem("af") === null) {
    autoFlaggingEnabled = 0;
  }
  const width = 25 * boardWidth;
  getElementById("p42").style.width = 4 + width + "px";
  const canvas = getElementById("gameCanvas");
  canvas.width = width;
  canvas.height = 25 * boardHeight;
  const faceImage = getElementById("gameFace");
  faceImage.src = faceGifs[0];
  const context = canvas.getContext("2d");
  for (let y = 0; y < boardHeight; y++) {
    for (let x = 0; x < boardWidth; x++) {
      context.drawImage(gameElementGifs[0], 25 * x, 25 * y);
    }
  }
  canvas.onmousedown = function (event) {
    // 处理鼠标按下事件，原函数调用: ot(event)
    handleMouseDown(event);
  };
  canvas.onmouseup = function (event) {
    // 处理鼠标抬起事件，原函数调用: rt(event)
    handleMouseUp(event);
  };
  canvas.ontouchstart = function (event) {
    // 处理触摸开始事件，原函数调用: at(event)
    handleTouchStart(event);
  };
  canvas.ontouchmove = function () {
    isMobile = 2;
    clearTimeout(touchTimer);
  };
  canvas.ontouchend = function (event) {
    // 处理触摸结束事件，原函数调用: ut(event)
    handleTouchEnd(event);
  };
  // 原函数调用: updateMineCount(extraBugs)
  updateRemainingMines(mineCount);
  // 原函数调用: updateTimer(0)
  updateElapsedTime(0);
  getElementById("autoFlagging").checked = parseInt(autoFlaggingEnabled);
}

// 游戏定时器，原变量名: E
let gameTimer;
// 开始时间，原变量名: startTime
let startTime;
// 当前时间，原变量名: currentTime
let currentTime;

/**
 * 停止游戏定时器
 * 原函数名: ft
 * @returns {number} - 游戏用时
 */
function stopGameTimer() {
  if (gameTimer > 0) {
    const endTime = Date.now();
    const elapsedTime = endTime - startTime;
    // 原函数调用: updateTimer(parseInt(elapsedTime / 1000))
    updateElapsedTime(parseInt(elapsedTime / 1000));
    clearInterval(gameTimer);
    gameTimer = 0;
    return Math.ceil(elapsedTime / 100);
  }
  return 0;
}

/**
 * 开始游戏定时器
 * 原函数名: st
 */
function startGameTimer() {
  startTime = Date.now();
  currentTime = 0;
  gameState = 1;
  gameTimer = setInterval(function () {
    // 原函数调用: updateTimer(++currentTime)
    updateElapsedTime(++currentTime);
  }, 1000);
}

/**
 * 标记格子
 * 原函数名: H
 * @param {number} x - 格子的横坐标
 * @param {number} y - 格子的纵坐标
 */
function flagCell(x, y) {
  isFirstClick = false;
  const cell = cellStates[y][x];
  if (cell[0] === 0) {
    if (remainingMines > 0) {
      if (cell[1] === 0) {
        // 检查逻辑，原函数调用: checkLogic()
        checkLogic();
      }
      const context = getElementById("gameCanvas").getContext("2d");
      context.drawImage(gameElementGifs[1], 25 * x, 25 * y);
      cell[0] = 2;
      // 原函数调用: updateMineCount(--remainingMines)
      updateRemainingMines(--remainingMines);
    }
  } else if (cell[0] === 2) {
    const context = getElementById("gameCanvas").getContext("2d");
    context.drawImage(gameElementGifs[0], 25 * x, 25 * y);
    cell[0] = 0;
    // 原函数调用: updateMineCount(++remainingMines)
    updateRemainingMines(++remainingMines);
  }
}

/**
 * 初始化游戏
 * 原函数名: start
 */
function initGame() {
  const baseUrl = getElementById("scoreboardLink").href + "#";
  const settings = localStorage.getItem("df5");
  if (settings === null) {
    getElementById("horizontalCells").value = 15;
    getElementById("verticalCells").value = 15;
    getElementById("mineCount").value = 20;
  } else {
    const settingsArray = settings.split(";");
    getElementById("horizontalCells").value = settingsArray[0];
    getElementById("verticalCells").value = settingsArray[1];
    getElementById("mineCount").value = settingsArray[2];
  }
  document.oncontextmenu = function () {
    return false;
  };
  document.onselectstart = function () {
    return false;
  };
  const canvas = getElementById("gameCanvas");
  const context = canvas.getContext("2d");
  // 原函数调用: updateMineCount = createDigitDisplay("mineCounter")
  updateRemainingMines = createDigitDisplay("remainingMinesCanvas");
  // 原函数调用: updateTimer = createDigitDisplay("timerDisplay")
  updateElapsedTime = createDigitDisplay("elapsedTimeCanvas");
  // 原函数调用: setGameDifficulty(localStorage.getItem("ch7"))
  setGameDifficulty(localStorage.getItem("ch7"));
  getElementById("userId").innerHTML = getUserName();
}

// 总格子数，原变量名: X
let totalCells;
// 游戏难度级别，原变量名: difficultyLevel
let gameDifficultyLevel;
// 屏幕宽度，原变量名: screenWidth
let screenWidth;
// 基础 URL，原变量名: baseUrl
let baseUrl;
// 用户昵称，原变量名: userNickname
let userNickname = null;

/**
 * 获取用户名称
 * 原函数名: dt
 * @returns {string} - 用户名称
 */
function getUserName() {
  if (userNickname !== null) {
    return userNickname;
  }
  const nick = localStorage.getItem("nick");
  if (nick !== null && nick !== "") {
    return nick;
  }
  return localStorage.getItem("uid");
}

/**
 * 设置游戏难度
 * 原函数名: _123
 * @param {number} level - 游戏难度级别
 */
function setGameDifficulty(level) {
  gameState = 0;
  screenWidth = document.body.clientWidth;
  screenHeight = document.body.clientHeight;
  gameDifficultyLevel = level = level === null ? screenWidth < 560 ? 1 : 2 : level;
  getElementById("custom").style.display = level === 5 ? "" : "none";
  if (level === 1) {
    boardWidth = boardHeight = 9;
    mineCount = 10;
    totalCells = 81;
  } else if (level === 2) {
    boardWidth = boardHeight = 16;
    mineCount = 40;
    totalCells = 256;
  } else if (level === 3) {
    mineCount = 99;
    boardWidth = screenHeight < screenWidth ? 30 : 16;
    boardHeight = screenHeight < screenWidth ? 16 : 30;
    totalCells = 480;
  } else if (level === 4) {
    boardWidth = parseInt((screenWidth - 18) / 25);
    boardHeight = parseInt((screenHeight - 54) / 25);
    totalCells = boardWidth * boardHeight;
    mineCount = totalCells >= 480 ? 0.20625 * totalCells : totalCells * totalCells / 5760 + totalCells / 8;
    mineCount = parseInt(mineCount);
  } else {
    if (level !== 5) return;
    boardWidth = parseInt(getElementById("horizontalCells").value);
    boardHeight = parseInt(getElementById("verticalCells").value);
    totalCells = boardWidth * boardHeight;
    mineCount = parseInt(getElementById("mineCount").value);
    if (totalCells < mineCount) {
      mineCount = totalCells;
    }
  }
  // 重置游戏，原函数调用: _45()
  resetGame();
  localStorage.setItem("ch7", level);
  getElementById("scoreboardLink").href = baseUrl + gameDifficultyLevel;
}

/**
 * 设置自定义难度
 * 原函数名: udf
 */
function setCustomDifficulty() {
  // 设置游戏难度，原函数调用: setGameDifficulty(5)
  setGameDifficulty(5);
  localStorage.setItem("df5", getElementById("horizontalCells").value + ";" + getElementById("verticalCells").value + ";" + getElementById("mineCount").value);
}

/**
 * 设置单选框的值
 * 原函数名: Y
 * @param {string} name - 单选框的名称
 * @returns {string} - 单选框的值
 */
function setRadioValue(name) {
  const value = localStorage.getItem(name);
  if (value === null) {
    value = 0;
  }
  const radios = document.getElementsByName(name);
  for (let i = 0; i < radios.length; i++) {
    if (radios[i].value === value) {
      radios[i].checked = true;
    }
  }
  return value;
}

// 选项名称数组，原变量名: optionNames
const optionNames = ["_mp1", "_mp2", "tpn", "opn"];

/**
 * 保存设置选项
 * 原函数名: _save
 * @param {number} index - 选项索引
 * @param {number} value - 选项值
 */
function saveOption(index, value) {
  const optionName = optionNames[index];
  if (value === 0) {
    localStorage.removeItem(optionName);
    value = null;
  } else {
    localStorage.setItem(optionName, value);
  }
  if (index === 0) {
    leftMouseButtonSetting = value;
  } else if (index === 1) {
    rightMouseButtonSetting = value;
  } else if (index === 2) {
    touchButtonSetting = value;
  } else {
    oneClickOpenSetting = value;
  }
}

/**
 * 显示更多触摸选项
 * 原函数名: smore
 * @param {number} option - 选项值
 */
function showMoreTouchOptions(option) {
  if (option === 0) {
    getElementById("markingOpenMethod").style.display = "block";
    getElementById("directOpenHint").style.display = "none";
  } else {
    getElementById("directOpenHint").style.display = "block";
    getElementById("markingOpenMethod").style.display = "none";
  }
}

/**
 * 切换鼠标设置显示
 * 原函数名: mouse2
 */
function toggleMouseSettings() {
  let visible = false;
  return function () {
    // 设置单选框的值，原函数调用: setRadioValue("_mp1")
    setRadioValue("_mp1");
    // 设置单选框的值，原函数调用: setRadioValue("_mp2")
    setRadioValue("_mp2");
    visible = !visible;
    getElementById("mouseSettings").style.display = visible ? "block" : "none";
    getElementById("mouseSettingsLink").innerText = visible ? "显示" : "设置";
  };
}

/**
 * 切换触摸设置显示
 * 原函数名: touch2
 */
function toggleTouchSettings() {
  let visible = false;
  return function () {
    const option = setRadioValue("tpn");
    // 设置单选框的值，原函数调用: setRadioValue("opn")
    setRadioValue("opn");
    // 显示更多触摸选项，原函数调用: showMoreTouchOptions(option)
    showMoreTouchOptions(option);
    visible = !visible;
    getElementById("touchSettings").style.display = visible ? "block" : "none";
    getElementById("touchSettingsLink").innerText = visible ? "显示" : "设置";
  };
}

/**
 * 切换重命名设置显示
 * 原函数名: setr
 */
function toggleRenameSettings() {
  let visible = false;
  return function () {
    visible = !visible;
    getElementById("userNickname").value = localStorage.getItem("nick");
    getElementById("renameSettings").style.display = visible ? "block" : "none";
    getElementById("setr").innerText = visible ? "显示" : "设置";
  };
}

/**
 * 设置背景颜色
 * 原函数名: bcolor
 */
function toggleNightMode() {
  const body = document.body;
  const links = document.getElementsByTagName("a");
  if (getElementById("nightMode").checked) {
    localStorage.setItem("night", "1");
    body.style.backgroundColor = "black";
    body.style.color = "silver";
    for (let i = 0; i < links.length; i++) {
      links[i].style.color = "silver";
    }
  } else {
    localStorage.removeItem("night");
    body.style.backgroundColor = "#f7f7f0";
    body.style.color = "";
    for (let i = 0; i < links.length; i++) {
      links[i].style.color = "";
    }
  }
}

/**
 * 应用夜间模式
 * 原函数名: night
 */
function applyNightMode() {
  if (localStorage.getItem("night") !== null) {
    getElementById("nightMode").checked = true;
    // 设置背景颜色，原函数调用: bcolor()
    toggleNightMode();
  }
}

/**
 * 报告问题
 * 原函数名: It
 * @param {number} type - 问题类型
 * @param {number} x - 格子的横坐标
 * @param {number} y - 格子的纵坐标
 */
function reportIssue(type, x, y) {
  // 原函数调用: sendHttpRequest("bug.php", version + ":" + type, function(response) {})
  sendHttpRequest("bug.php", version + ":" + type, function (response) {});
}

// 初始化更新剩余地雷数量的函数
let updateRemainingMines;
// 初始化更新游戏用时的函数
let updateElapsedTime;